/*
 *   Http 통신을 컨트롤하는 역할을 담당
 */
package com.example.rhbloodmod;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xmlpull.v1.XmlPullParser;

import android.util.Log;

public class HttpAPIHelperHandler {
	private static final String DEBUG_TAG = "Test";
	private static ArrayList<NameValuePair> queryStringParams;
    static{
    	queryStringParams = new ArrayList<NameValuePair>();
    }
    /*
     *  Java Net API를 사용한 서버 요청 처리
     */
    public static String insertBloodInfoJavaNetRequestToServer(BloodEntityObject bloodInfo){
    	
 	    //파싱되어 넘어온 결과 값을 리턴
 	    String bloodInsertResultValue = null;
 	    StringBuilder queryStringParams = new StringBuilder();
 	    //쿼리문자열을 조합한다
 	    queryStringParams
 	           .append("patientName="+bloodInfo.patientName)
 	           .append("&bloodType=" + bloodInfo.bloodType)
 	           .append("&statusText=" + bloodInfo.statusText)
 	           .append("&donationType="+ bloodInfo.donationType)
 	           .append("&bloodValue=" + bloodInfo.bloodValue)
 	           .append("&hospital=" +bloodInfo.hospital)
 	           .append("&hospitalPhone=" +bloodInfo.hospitalPhone)
 	           .append("&relationText=" +bloodInfo.relationText)
 	           .append("&careName=" + bloodInfo.careName)
 	           .append("&carePhone=" + bloodInfo.carePhone);
 	    HttpURLConnection httpConnection = null;
 	    OutputStream toServer = null;
 	    InputStream fromServer = null;
 	    try{
 	    	//서버와의 커넥션객체를 얻어온다
 	    	httpConnection = 
 	    			HttpConnectionManager.getHttpURLConnection(
 	    					    NetworkDefineConstant.SERVER_URL_BLOOD_INSERT);
 	    	
 	    	//서버와의 출력스트림을 연결 한다
 	    	toServer = httpConnection.getOutputStream();
 	    	//쿼리 문자열을 보낸다
 	    	toServer.write(queryStringParams.toString().getBytes("UTF-8"));
 	    	toServer.flush();
 	    	if( toServer != null){
 	    		toServer.close();
 	    	}
 	    	int responseCode = httpConnection.getResponseCode();
 	    	
 	    	if(responseCode >= 200 && responseCode < 300 ){
 	    		fromServer = httpConnection.getInputStream();
 	    		XmlPullParser responsePullParser = XMLPullParserManager.generateXMLPullParser();
				responsePullParser.setInput(fromServer,HTTP.UTF_8);			
				//넘어온 XML을 파싱하여 결과값을 리턴 한다
				bloodInsertResultValue = ResponseXMLParser.parsingBloodInsertResultXML(responsePullParser);
 	    	}else{ //응답코드가 200번대가 아닐경우
 	    	//, , , ,
 	    	} 	    	
 	    }catch(Exception e){
 	    	Log.e(DEBUG_TAG, " insertBloodInfoJavaNetRequestToServer() 에서 발생! " , e);
 	    }finally{
 	    	if(toServer != null){
 	    		try{
 	    			toServer.close();
 	    		}catch(IOException ioe){}
 	    	}
 	    	if(fromServer != null){
 	    		try{
 	    			fromServer.close();
 	    		}catch(IOException ioe){}
 	    	}
 	    	if( httpConnection != null){
 	    		httpConnection.disconnect(); //자원 반납
 	    	}
 	    }
    	return bloodInsertResultValue;
    }
    
//    public static ArrayList<String> fetchBloodInfoJavaNetRequestFromServer(){
    public static ArrayList<BloodEntityObject> fetchBloodInfoJavaNetRequestFromServer(){

//    	ArrayList<String> entityFromXml=null;
    	ArrayList<BloodEntityObject> entityFromXml=null;
 	    //파싱되어 넘어온 결과 값을 리턴
 	    String bloodInsertResultValue = null;
 	    StringBuilder queryStringParams = new StringBuilder();

 	    HttpURLConnection httpConnection = null;
 	    OutputStream toServer = null;
 	    InputStream fromServer = null;
 	    StringBuilder result = new StringBuilder();
 	    try{
 	    	//서버와의 커넥션객체를 얻어온다
 	    	httpConnection = 
 	    			HttpConnectionManager.getHttpURLConnection(
 	    					NetworkDefineConstant.SERVER_URL_BLOOD_ALL_SELECT);
 	    	
// 	    	//서버와의 출력스트림을 연결 한다
// 	    	toServer = httpConnection.getOutputStream();
// 	    	//쿼리 문자열을 보낸다
// 	    	toServer.write(queryStringParams.toString().getBytes("UTF-8"));
// 	    	toServer.flush();
// 	    	if( toServer != null){
// 	    		toServer.close();
// 	    	}
 	    	int responseCode = httpConnection.getResponseCode();
 	    	Log.i("Test", responseCode+"응답코드");
 	    	if(responseCode >= 200 && responseCode < 300 ){
 	    		fromServer = httpConnection.getInputStream();
 	    		BufferedReader br= new BufferedReader(new InputStreamReader(fromServer, "UTF-8"));
 	    		while (true) {
					String line = br.readLine();
					if (line ==null) break;
					result.append(line+'\n');
				}
 	    		Log.i("Test", result.toString());
 	    		br.close();
// 	    		XmlPullParser responsePullParser = XMLPullParserManager.generateXMLPullParser();
//				responsePullParser.setInput(fromServer,HTTP.UTF_8);			
				//넘어온 XML을 파싱하여 결과값을 리턴 한다
 	    		entityFromXml = ResponseXMLParser.parsingBloodRequestList(result);
// 	    		entityFromXml = ResponseXMLParser.parsingBloodRequestList(responsePullParser);
 	    	}else{ //응답코드가 200번대가 아닐경우
 	    	//, , , ,
 	    	} 	    	
 	    }catch(Exception e){
 	    	Log.e(DEBUG_TAG, " fetchBloodInfoJavaNetRequestFromServer() 에서 발생! " , e);
 	    }finally{
 	    	if(toServer != null){
 	    		try{
 	    			toServer.close();
 	    		}catch(IOException ioe){}
 	    	}
 	    	if(fromServer != null){
 	    		try{
 	    			fromServer.close();
 	    		}catch(IOException ioe){}
 	    	}
 	    	if( httpConnection != null){
 	    		httpConnection.disconnect(); //자원 반납
 	    	}
 	    }
//    	for (int i=0; i<entityFromXml.size(); i++){
//    		Log.i("Test", i+ ":"+ entityFromXml.get(i));
//    	}
//    	return result.toString();
    	return entityFromXml;
        	
    }
    
	/*
	 * 혈액 요청 서버 입력 요청
	 * Apache HttpClient API 사용
	 */
   public static String insertBloodInfoApacheHttpClientToServer(
		   BloodEntityObject bloodInfo){
	  //전에 설정한 쿼리문자열이 있다면 비운다   
	   if(queryStringParams.size() > 0 ){
		   queryStringParams.removeAll(queryStringParams);
	   }
	   //Query String을 세팅하기 위함
	   queryStringParams.add(new BasicNameValuePair("patientName", bloodInfo.patientName));
	   queryStringParams.add(new BasicNameValuePair("bloodType", bloodInfo.bloodType));
	   queryStringParams.add(new BasicNameValuePair("statusText", bloodInfo.statusText));
	   queryStringParams.add(new BasicNameValuePair("donationType", bloodInfo.donationType));
	   queryStringParams.add(new BasicNameValuePair("bloodValue", bloodInfo.bloodValue));
	   queryStringParams.add(new BasicNameValuePair("hospital", bloodInfo.hospital));
	   queryStringParams.add(new BasicNameValuePair("hospitalPhone", bloodInfo.hospitalPhone));
	   queryStringParams.add(new BasicNameValuePair("relationText", bloodInfo.relationText));
	   queryStringParams.add(new BasicNameValuePair("careName", bloodInfo.careName));
	   queryStringParams.add(new BasicNameValuePair("carePhone", bloodInfo.carePhone));

	   HttpClient httpClient = null;
	   //응답내용을 스트림으로 받기 위함
	   InputStream xmlDataFromServer = null;
	   //파싱되어 넘어온 결과 값을 리턴
	   String bloodInsertResultValue = null;
	   HttpPost httpPost = null;
	   try{
		   //웹서버로의 요청을 담당할 커넥션 객체를 얻는다
		   httpClient = HttpConnectionManager.getGenerateHttpClient();
		   //POST방식의 요청을 선택
		   httpPost = new HttpPost(NetworkDefineConstant.SERVER_URL_BLOOD_INSERT);
		  //요청 파라미터를 Request Content Body에 �팅
		  UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(queryStringParams, HTTP.UTF_8);
		  httpPost.setEntity(formEntity);
		  
		  //5초동한  Connection객체가 Idle상태에 빠지면 자동 close
		  httpClient.getConnectionManager().closeIdleConnections(5000, TimeUnit.MILLISECONDS);
		  //웹서버로 요청후 응답 객체를 받아 온다.
		  HttpResponse httpResponse = httpClient.execute(httpPost);
		  //응답 상태코드
		   int responseCode = httpResponse.getStatusLine().getStatusCode();
		   HttpEntity responseBody = null;
			//정상적인 응답 이라면
			if( responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_ACCEPTED  ){
				
				//응답의 보디객체를 가져온다
				responseBody = httpResponse.getEntity();
				//응답보디객체의 내용을 가져온다(서버로 부터 넘어온 XML 데이터)
				xmlDataFromServer =  responseBody.getContent();
		        
				//파서객체를 얻어 넘어온 XML을 파싱한다
				XmlPullParser responsePullParser = XMLPullParserManager.generateXMLPullParser();
				responsePullParser.setInput(xmlDataFromServer,HTTP.UTF_8);
				
				//넘어온 XML을 파싱하여 결과값을 리턴 한다
				bloodInsertResultValue = 
						ResponseXMLParser.parsingBloodInsertResultXML(responsePullParser);
			//서버에서의 응답이 2XX번대가 아닐 경우의 에러처리 코드를 삽입
			}else{
			 //, , , ,
			}
	   }catch(Exception e){
		   Log.e(DEBUG_TAG, "insertBloodInfoRequestToServer(BloodEntityObject) --발생--  ", e);
	   }finally{
		   if( xmlDataFromServer != null){
				try{
					xmlDataFromServer.close();
				}catch(IOException ioe){}
			}
		   if( httpPost != null ){
			   httpPost.abort();
		   }
		   if( httpClient != null){
			   HttpConnectionManager.releaseConnection(httpClient);
			   
		   }
	   }
	   //파싱된 결과값을 리턴
	   return bloodInsertResultValue;
   }
}